package ua.cs.stu.ics.label;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: 22.02.11
 * Time: 0:57
 * To change this template use File | Settings | File Templates.
 */
public class MyMouseAdapter extends MouseAdapter {
    private Point initLabelLocation = null;
    private Point initMouseLocationOnScreen = null;

    @Override
    public void mousePressed(MouseEvent e) {
        JLabelExtended label = (JLabelExtended) e.getSource();

        if (e.getButton() == 3) {
            label.popupMove.show(e.getComponent(), e.getX(), e.getY());
        } else {
            if (e.getButton() == 1) {
                // get label's initial location relative to its container
                initLabelLocation = label.getLocation();

                // get Mouse's initial location relative to the screen
                initMouseLocationOnScreen = e.getLocationOnScreen();
            }
        }

    }

    @Override
    public void mouseReleased(MouseEvent e) {
        if (e.getButton() == 1) {
            initLabelLocation = null;
            initMouseLocationOnScreen = null;
        }
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        if (e.getButton() == 0) {
            // if not dragging a JLabel
            if (initLabelLocation == null || initMouseLocationOnScreen == null) {
                return;
            }
            JLabel label = (JLabel) e.getSource();

            // get mouse's new location relative to the screen
            Point mouseLocation = e.getLocationOnScreen();

            // and see how this differs from the initial location.
            int deltaX = mouseLocation.x - initMouseLocationOnScreen.x;
            int deltaY = mouseLocation.y - initMouseLocationOnScreen.y;

            // change label's position by the same difference, the "delta" vector
            int labelX = initLabelLocation.x + deltaX;
            int labelY = initLabelLocation.y + deltaY;

            label.setLocation(labelX, labelY);
        }
    }
}

